﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Newtonsoft.Json;

namespace Base.Common
{
    public class ConvertHelper
    {
        #region XML转义字符处理
        /// <summary>
        /// XML转义字符处理
        /// </summary>
        public static string ConvertXml(string xml)
        {

            xml = (char)1 + xml;   //为了避免首字母为要替换的字符，前加前缀

            for (int intNext = 0; true; )
            {
                int intIndexOf = xml.IndexOf("&", intNext);
                intNext = intIndexOf + 1;  //避免&被重复替换
                if (intIndexOf <= 0)
                {
                    break;
                }
                else
                {
                    xml = xml.Substring(0, intIndexOf) + "&amp;" + xml.Substring(intIndexOf + 1);
                }
            }

            for (; true; )
            {
                int intIndexOf = xml.IndexOf("<");
                if (intIndexOf <= 0)
                {
                    break;
                }
                else
                {
                    xml = xml.Substring(0, intIndexOf) + "&lt;" + xml.Substring(intIndexOf + 1);
                }
            }

            for (; true; )
            {
                int intIndexOf = xml.IndexOf(">");
                if (intIndexOf <= 0)
                {
                    break;
                }
                else
                {
                    xml = xml.Substring(0, intIndexOf) + "&gt;" + xml.Substring(intIndexOf + 1);
                }
            }

            for (; true; )
            {
                int intIndexOf = xml.IndexOf("\"");
                if (intIndexOf <= 0)
                {
                    break;
                }
                else
                {
                    xml = xml.Substring(0, intIndexOf) + "&quot;" + xml.Substring(intIndexOf + 1);
                }
            }

            return xml.Replace(((char)1).ToString(), "");

        }
        #endregion

        #region DataSet格式转JSON
        /// <summary>
        /// 将DataSet转换成json格式
        /// </summary>
        /// <param name="ds">要转换的DataSet(参数DataSet必须是调用了SQLHelper.PageData()函数后返回的Dataset)</param>
        /// <returns></returns>
        public static string GetJSON(DataSet ds)
        {
            return GetJSON(ds.Tables[1], (int)ds.Tables[0].Rows[0][0]);
        }
        /// <summary>
        /// 将DataTable转换成json格式
        /// </summary>
        /// <param name="dt">要转换的datatable(在没有进行数据分页的情况下可以使用此方法)</param>
        /// <returns></returns>
        public static string GetJSON(DataTable dt)
        {
            return GetJSON(dt, dt.Rows.Count);
        }
        /// <summary>
        /// 将DataTable转换成json格式
        /// </summary>
        /// <param name="dt">要转换的datatable</param>
        /// <param name="totalCount">数据的总条数【如果进行了数据分页，则此数字不一定等于第一个参数datatable中的行数(datatable.rows.count)】</param>
        /// <returns></returns>
        public static string GetJSON(DataTable dt, int totalCount)
        {
            StringBuilder JsonString = new StringBuilder();

            //Exception Handling
            if (dt != null && dt.Rows.Count > 0)
            {
                JsonString.Append("{ ");
                JsonString.Append("\"Total\":\"" + totalCount + "\",Data:[");

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    JsonString.Append("{ ");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (j < dt.Columns.Count - 1)
                        {
                            JsonString.AppendFormat("\"{0}\":\"{1}\",",
                                jsonReplace(dt.Columns[j].ColumnName.ToString()),
                                jsonReplace(dt.Rows[i][j].ToString()));
                        }
                        else if (j == dt.Columns.Count - 1)
                        {
                            JsonString.AppendFormat("\"{0}\":\"{1}\"",
                                jsonReplace(dt.Columns[j].ColumnName.ToString()),
                                jsonReplace(dt.Rows[i][j].ToString()));
                        }
                    }

                    /*end Of String*/
                    if (i == dt.Rows.Count - 1)
                    {
                        JsonString.Append("} ");
                    }
                    else
                    {
                        JsonString.Append("}, ");
                    }
                }
                JsonString.Append("]}");
                return JsonString.ToString();
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 将DataTable转换成json格式
        /// </summary>
        /// <param name="dt">要转换的datatable</param>
        /// <returns></returns>
        public static string GetTreeJSON(DataTable dt)
        {
            StringBuilder JsonString = new StringBuilder();
            JsonString.Append("[");
            //Exception Handling
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    JsonString.Append("{ ");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (j < dt.Columns.Count - 1)
                        {
                            JsonString.AppendFormat("\"{0}\":\"{1}\",",
                                jsonReplace(dt.Columns[j].ColumnName.ToString()),
                                jsonReplace(dt.Rows[i][j].ToString()));
                        }
                        else if (j == dt.Columns.Count - 1)
                        {
                            JsonString.AppendFormat("\"{0}\":\"{1}\"",
                                jsonReplace(dt.Columns[j].ColumnName.ToString()),
                                jsonReplace(dt.Rows[i][j].ToString()));
                        }
                    }

                    /*end Of String*/
                    if (i == dt.Rows.Count - 1)
                    {
                        JsonString.Append("} ");
                    }
                    else
                    {
                        JsonString.Append("}, ");
                    }
                }
                JsonString.Append("]");
                return JsonString.ToString();
            }
            else
            {
                return null;
            }
        }

        private static string jsonReplace(string old)
        {
            string[] oldChar = new string[4] { "'", "\"", "\n", "\r\n" };
            string[] newChar = new string[4] { "\\'", "\\\"", "\\u000a", "\\u000d\\u000a" };

            for (int i = 0; i < oldChar.Length; i++)
            {
                old = old.Replace(oldChar[i], newChar[i]);
            }
            return old;
        }
        /// <summary>
        /// 将DataTable转化为实体类数组
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="dt">DataTable</param>
        /// <returns>实体类数组</returns>
        public static List<T> DataTableToList<T>(System.Data.DataTable dt) where T : new()
        {
            List<T> list = new List<T>();
            foreach (System.Data.DataRow row in dt.Rows)
            {
                var entity = new T();
                System.Reflection.PropertyInfo[] fields = entity.GetType().GetProperties();

                foreach (var field in fields)
                {
                    if (dt.Columns.Contains(field.Name))
                    {
                        var val = row[field.Name];
                        if (val is DBNull)
                            continue;

                        var type = field.GetType();

                        if (type == typeof(String))
                            val = val.ToString();
                        else if (type == typeof(DateTime))
                            val = (DateTime?)row[field.Name];
                        else if (type == typeof(Decimal))
                            val = (decimal)row[field.Name];

                        field.SetValue(entity, val, null);
                    }
                }
                list.Add(entity);
            }
            dt.Dispose();
            return list;
        }
        #endregion


        public static Guid GetGuid(string value)
        {
            try
            {
                return Guid.Parse(value);
            }
            catch (Exception)
            {
                return Guid.Empty;
            }
        }

        public static string GetString(object value)
        {
            return Convert.ToString(value);
        }

        public static decimal GetDecimal(object value)
        {
            decimal result = 0m;
            decimal.TryParse(GetString(value), out result);
            return result;
        }

        public static int GetInt(object value)
        {
            int result = 0;
            int.TryParse(GetString(value), out result);
            return result;
        }

        public static float GetFloat(object value)
        {
            float result = 0f;
            float.TryParse(GetString(value), out result);
            return result;
        }

        public static double GetDouble(object value)
        {
            double result = 0;
            double.TryParse(GetString(value), out result);
            return result;
        }

        public static Guid GetGuid(object value)
        {
            try
            {
                return new Guid(GetString(value));
            }
            catch { }
            return Guid.Empty;
        }

        public static DateTime GetDateTime(object value)
        {
            DateTime result = DateTime.MinValue;
            DateTime.TryParse(GetString(value), out result);
            return result;
        }

        public static bool GetBool(object value)
        {
            bool result = false;
            bool.TryParse(GetString(value), out result);
            return result;
        }

        /// <summary>
        /// 对象转换成json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonObject">需要格式化的对象</param>
        /// <returns>Json字符串</returns>
        public static string ObjectToJson<T>(T jsonObject)
        {
            return JsonConvert.SerializeObject(jsonObject);
        }

        /// <summary>
        /// json字符串转换成对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json">要转换成对象的json字符串</param>
        /// <returns></returns>
        public static T JsonToObject<T>(string json)
        {
            return JsonConvert.DeserializeObject<T>(json);
        }
    }
}
